<template>
  <div class="form-container">
    <el-card class="box-card" v-if="!submitSuccess">
      <div slot="header" class="clearfix">
        <h1 style="text-align: center;">订单需求提交</h1>
        <h2 style="color: #d9534f; font-weight: bold; ">🐳温馨提示：</h2>
        <p
          style="color: #d9534f; font-weight: bold; background-color: #f2dede; padding: 10px; border-left: 4px solid #d9534f;">
          为保障每位用户的独特体验，避免小范围内出现样式相似的情况，建议您认真填写真实信息哦~ <br>
        <!-- </p>
        <p -->
          <!-- style="color: #d9534f; font-weight: bold; background-color: #f2dede; padding: 10px; border-left: 4px solid #d9534f;"> -->
          当信息真实完整时，我们将能更好地为您创建专属样式，感谢您的理解与配合！
        </p>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="项目标题" prop="orderTitle">
          <el-input v-model="form.orderTitle" placeholder="例如: XX在线购物系统" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="您的称呼" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入您的姓名或称呼" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="联系电话" prop="customerPhone">
              <el-input v-model="form.customerPhone" placeholder="请输入您的联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="学校" prop="school">
              <el-input v-model="form.school" placeholder="例如: 江苏省南京市南京大学" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="专业" prop="specialty">
              <el-input v-model="form.specialty" placeholder="请输入您的专业" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select v-model="form.projectType" placeholder="请选择项目类型" style="width:100%;">
                <el-option label="毕业设计" value="毕业设计" />
                <el-option label="个人项目" value="个人项目" />
                <el-option label="商用项目" value="商用项目" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="技术类型" prop="techType">
              <el-select v-model="form.techType" placeholder="请选择技术类型" style="width:100%;" filterable>
                <el-option v-for="item in techTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="交付物" prop="deliverable">
              <el-select v-model="form.deliverable" placeholder="请选择交付物" style="width:100%;" filterable multiple
                collapse-tags>
                <el-option v-for="item in deliverableOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="期望金额(元)" prop="rewardAmount">
              <el-input-number v-model="form.rewardAmount" :precision="2" :step="100" :min="0"
                style="width:100%;"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-form-item label="截止日期" prop="estimatedEndTime">
              <el-date-picker clearable v-model="form.estimatedEndTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择期望截止日期" style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="硬件环境" prop="hardware">
          <el-input v-model="form.hardware" type="textarea" :rows="2" placeholder="例如：Windows 11, MySQL 8.0, JDK 1.8" />
        </el-form-item>
        <el-form-item label="需求简介" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" :rows="5" placeholder="请详细描述您的项目需求、功能点等" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">立即提交</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card" v-if="submitSuccess">
      <div class="success-message">
        <h3>提交成功！</h3>
        <p>感谢您的提交，我们的售前工程师将尽快与您联系，请保持电话畅通。</p>
        <i class="el-icon-success"></i>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getSubmissionByToken, submitByToken } from "@/api/dashboard/public_submissions";
import { login } from "@/api/login";
import { setToken, setExpiresIn } from "@/utils/auth";

export default {
  name: "SubmissionForm",
  data() {
    return {
      loading: false,
      submitSuccess: false,
      authToken: null, // 添加认证token字段
      form: {
        submissionToken: null,
        customerName: null,
        customerPhone: null,
        orderTitle: null,
        school: null,
        specialty: null,
        projectType: "毕业设计",
        hardware: null,
        introduce: null,
        techType: null,
        deliverable: [],
        estimatedEndTime: null,
        rewardAmount: 0,
      },
      techTypeOptions: [
        { value: 'JAVA', label: 'JAVA' },
        { value: 'Python', label: 'Python' },
        { value: 'Android', label: 'Android' },
        { value: '嵌入式', label: '嵌入式' },
        { value: 'Labview', label: 'Labview' },
        { value: '单片机', label: '单片机' },
        { value: '前端', label: '前端' },
        { value: '小程序', label: '小程序' },
        { value: '开源硬件', label: '开源硬件' },
        { value: 'H5', label: 'H5' },
        { value: 'UI', label: 'UI' },
        { value: 'PHP', label: 'PHP' },
        { value: 'Matlab', label: 'Matlab' },
        { value: 'C#', label: 'C#' },
        { value: 'C++', label: 'C++' },
        { value: 'Solidity', label: 'Solidity' },
        { value: 'DSP', label: 'DSP' },
        { value: '论文', label: '论文' },
        { value: 'Hadoop', label: 'Hadoop' },
        { value: 'QT', label: 'QT' },
        { value: 'Go', label: 'Go' },
        { value: 'C语言', label: 'C语言' }
      ],
      deliverableOptions: [
        { value: '开题', label: '开题' },
        { value: '任务书', label: '任务书' },
        { value: 'PPT', label: 'PPT' },
        { value: '配套论文(100元)', label: '配套论文(100元)' },
        { value: '定制论文（和客服沟通价格）', label: '定制论文（和客服沟通价格）' },
        { value: '程序', label: '程序' },
        { value: '实物', label: '实物' },
        { value: '原理图', label: '原理图' },
        { value: 'PCB图', label: 'PCB图' },
        { value: '电路图', label: '电路图' },
      ],
      rules: {
        customerName: [
          { required: true, message: "请输入您的称呼", trigger: "blur" },
          { pattern: /^[a-zA-Z\u4e00-\u9fa5\s]{2,20}$/, message: '请输入2-20个中英文字符', trigger: 'blur' }
        ],
        customerPhone: [
          { required: true, message: "请输入您的联系电话", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
        ],
        orderTitle: [{ required: true, message: "请输入项目标题", trigger: "blur" }],
        school: [{ required: true, message: "请输入真实的学校", trigger: "blur" }],
        specialty: [{ required: true, message: "请输入真实的专业", trigger: "blur" }],
        introduce: [{ required: true, message: "请详细描述您的需求", trigger: "blur" }],
        techType: [{ required: true, message: "请选择期望的技术类型", trigger: "change" }],
        estimatedEndTime: [{ required: true, message: "请选择期望的截止日期", trigger: "change" }],
        rewardAmount: [{ required: true, message: "请输入您的预算金额", trigger: "blur" }],
      },
    };
  },
  created() {
    const token = this.$route.params.token;
    if (token) {
      this.form.submissionToken = token;
    } else {
      this.$modal.alertError("无效的链接！");
    }
  },
  methods: {
    // 添加自动登录方法
    async autoLogin() {
      try {
        const loginData = {
          username: "客户提交订单账号",
          password: "123456"
        };
        const response = await login(loginData.username, loginData.password);
        if (response && response.data && response.data.access_token) {
          this.authToken = response.data.access_token;
          // 使用正确的方式存储token到Cookies中
          setToken(response.data.access_token);
          setExpiresIn(response.data.expires_in);
          return true;
        }
        return false;
      } catch (error) {
        console.error('自动登录失败:', error);
        this.$modal.alertError("系统登录失败，请稍后重试！");
        return false;
      }
    },
    
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true;
          
          // 如果没有token，先进行自动登录
          if (!this.authToken) {
            const loginSuccess = await this.autoLogin();
            if (!loginSuccess) {
              this.loading = false;
              return;
            }
          }
          
          const dataToSubmit = { ...this.form };
          if (Array.isArray(dataToSubmit.deliverable)) {
            dataToSubmit.deliverable = dataToSubmit.deliverable.join(',');
          }
          
          try {
            const response = await submitByToken(dataToSubmit);
            this.loading = false;
            this.submitSuccess = true;
          } catch (error) {
            this.loading = false;
            this.$modal.alertError("提交失败，请检查网络连接或稍后重试！");
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style scoped>
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
  padding: 20px;
}

.box-card {
  width: 100%;
  max-width: 800px;
}

.clearfix h2 {
  margin: 0;
  font-size: 24px;
}

.clearfix p {
  color: #909399;
  margin-top: 8px;
}

.success-message {
  text-align: center;
  padding: 40px;
}

.success-message h3 {
  font-size: 28px;
  color: #67c23a;
}

.success-message p {
  color: #606266;
  font-size: 16px;
}

.success-message .el-icon-success {
  font-size: 80px;
  color: #67c23a;
  margin-top: 20px;
}
</style>